"use server";
import { PrismaClient } from "@prisma/client";

// excludeId 是指，除了这个 id 以外的所有数据
export async function queryExist(name, excludeId = null) {
  const prisma = new PrismaClient();

  const driver = await prisma.driver.findUnique({
    where: {
      name: name,
    },
  });

  // 排除 excludeId
  if (excludeId) {
    if (driver && driver.id !== excludeId) {
      return {
        status: "error",
        message: "驱动名称已存在",
      };
    } else {
      return {
        status: "success",
      };
    }
  }

  if (driver) {
    return {
      status: "error",
      message: "驱动名称已存在",
    };
  }

  // return success
  return {
    status: "success",
  };
}

export async function addDriver(formData) {
  const name = formData.get("name");
  const memo = formData.get("memo");

  // query if name exist
  const exist = await queryExist(name);
  if (exist && exist.status === "error") {
    return {
      message: "驱动名称已存在",
    };
  }

  const prisma = new PrismaClient();

  // add driver
  const driver = await prisma.driver.create({
    data: {
      name: name,
      memo: memo,
    },
  });

  // close prisma
  await prisma.$disconnect();

  // return result
  if (driver) {
    return {
      message: "添加成功",
    };
  } else {
    return {
      message: "添加失败",
    };
  }
}

export async function deleteDriver(id) {
  const prisma = new PrismaClient();

  await prisma.driver.delete({
    where: {
      id: id,
    },
  });

  await prisma.$disconnect();
}

export async function allDriver() {
  const prisma = new PrismaClient();

  const drivers = await prisma.driver.findMany();

  await prisma.$disconnect();

  return drivers;
}

// get driver by id
export async function getDriver(id) {
  const prisma = new PrismaClient();

  if (!id) return;

  const driver = await prisma.driver.findUnique({
    where: {
      id: id,
    },
  });

  await prisma.$disconnect();

  return driver;
}

export async function updateDriver(id, formData) {
  if (!id) return;

  const prisma = new PrismaClient();

  const name = formData.get("name");
  const memo = formData.get("memo");

  const driver = await prisma.driver.update({
    where: {
      id: id,
    },
    data: {
      name: name,
      memo: memo,
    },
  });

  await prisma.$disconnect();

  return driver;
}
